from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.services.xiaohongshu_service import xiaohongshu_service
from app.crud.crud_xiaohongshu import (
    xiaohongshu_account_crud,
    xiaohongshu_publish_log_crud,
    xiaohongshu_token_crud
)
from app.schemas.xiaohongshu import (
    LoginRequest,
    LoginResponse,
    LoginStatusResponse,
    PublishRequest,
    PublishResponse,
    XiaohongshuAccount,
    XiaohongshuAccountCreate,
    XiaohongshuAccountUpdate,
    XiaohongshuPublishLog,
    AccountListResponse,
    PublishLogListResponse,
    StatsResponse,
    AccountStats,
    PublishStats
)
import logging
import json
from datetime import datetime

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/login/open", response_model=LoginResponse)
async def open_login_page(request: LoginRequest = None):
    """打开登录页面"""
    try:
        result = await xiaohongshu_service.open_login_page()
        return LoginResponse(
            success=result["success"],
            message=result["message"],
            qr_code_url=result.get("qr_code_url")
        )
    except Exception as e:
        logger.error(f"打开登录页面失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/login/status", response_model=LoginStatusResponse)
async def check_login_status(db: Session = Depends(get_db)):
    """检查登录状态"""
    try:
        result = await xiaohongshu_service.check_login_status()
        
        # 如果已登录，获取当前账号信息
        current_account = None
        if result.get("is_logged_in", False):
            current_account = xiaohongshu_account_crud.get_current_account(db)
        
        return LoginStatusResponse(
            success=result["success"],
            is_logged_in=result.get("is_logged_in", False),
            message=result["message"],
            account=current_account
        )
    except Exception as e:
        logger.error(f"检查登录状态失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/login/save", response_model=LoginResponse)
async def save_login_info(db: Session = Depends(get_db)):
    """保存登录信息"""
    try:
        # 获取登录信息
        result = await xiaohongshu_service.get_login_info()
        
        if not result["success"]:
            return LoginResponse(
                success=False,
                message=result["message"]
            )
        
        data = result["data"]
        nickname = data.get("nickname", "")
        account_name = data.get("account_name", "")
        following = data.get("following", "0")
        followers = data.get("followers", "0")
        cookies = data.get("cookies", "")
        
        # 检查账号是否已存在（通过昵称或账号名）
        existing_account = None
        if account_name:
            # 先通过账号名查找
            existing_account = db.query(xiaohongshu_account_crud.model).filter(
                xiaohongshu_account_crud.model.account_name == account_name
            ).first()
        
        if not existing_account and nickname:
            # 再通过昵称查找
            existing_account = db.query(xiaohongshu_account_crud.model).filter(
                xiaohongshu_account_crud.model.nickname == nickname
            ).first()
        
        if existing_account:
            # 更新现有账号
            update_data = {
                "nickname": nickname or existing_account.nickname,
                "account_name": account_name or existing_account.account_name,
                "following": following,
                "followers": followers,
                "cookies": cookies,
                "last_login": datetime.utcnow()
            }
            
            xiaohongshu_account_crud.update(db, db_obj=existing_account, obj_in=update_data)
            
            # 设置为当前账号
            xiaohongshu_account_crud.set_current_account(db, account_id=existing_account.id)
            
            account = existing_account
        else:
            # 创建新账号
            account_data = {
                "nickname": nickname or f"用户_{datetime.now().strftime('%Y%m%d%H%M%S')}",
                "account_name": account_name,
                "following": following,
                "followers": followers,
                "cookies": cookies,
                "is_current": True
            }
            
            # 先将所有账号设为非当前
            db.query(xiaohongshu_account_crud.model).update({"is_current": False})
            db.commit()
            
            account = xiaohongshu_account_crud.create(db, obj_in=account_data)
        
        return LoginResponse(
            success=True,
            message="登录信息保存成功",
            account=account
        )
        
    except Exception as e:
        logger.error(f"保存登录信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/accounts", response_model=AccountListResponse)
def get_accounts(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取账号列表"""
    try:
        accounts = xiaohongshu_account_crud.get_multi(db, skip=skip, limit=limit)
        total = db.query(xiaohongshu_account_crud.model).count()
        
        return AccountListResponse(
            success=True,
            accounts=accounts,
            total=total
        )
    except Exception as e:
        logger.error(f"获取账号列表失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/accounts/current", response_model=XiaohongshuAccount)
def get_current_account(db: Session = Depends(get_db)):
    """获取当前账号"""
    try:
        account = xiaohongshu_account_crud.get_current_account(db)
        if not account:
            raise HTTPException(status_code=404, detail="未找到当前账号")
        return account
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取当前账号失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/accounts/{account_id}/set-current")
def set_current_account(account_id: int, db: Session = Depends(get_db)):
    """设置当前账号"""
    try:
        account = xiaohongshu_account_crud.get(db, id=account_id)
        if not account:
            raise HTTPException(status_code=404, detail="账号不存在")
        
        success = xiaohongshu_account_crud.set_current_account(db, account_id=account_id)
        if not success:
            raise HTTPException(status_code=500, detail="设置当前账号失败")
        
        return {"success": True, "message": "设置成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"设置当前账号失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/accounts/{account_id}", response_model=XiaohongshuAccount)
def update_account(account_id: int, account_update: XiaohongshuAccountUpdate, db: Session = Depends(get_db)):
    """更新账号信息"""
    try:
        account = xiaohongshu_account_crud.get(db, id=account_id)
        if not account:
            raise HTTPException(status_code=404, detail="账号不存在")
        
        updated_account = xiaohongshu_account_crud.update(db, db_obj=account, obj_in=account_update)
        return updated_account
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新账号失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/accounts/{account_id}")
def delete_account(account_id: int, db: Session = Depends(get_db)):
    """删除账号"""
    try:
        account = xiaohongshu_account_crud.get(db, id=account_id)
        if not account:
            raise HTTPException(status_code=404, detail="账号不存在")
        
        xiaohongshu_account_crud.remove(db, id=account_id)
        return {"success": True, "message": "删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除账号失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/publish", response_model=PublishResponse)
async def publish_post(request: PublishRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)):
    """发布图文内容"""
    try:
        # 获取账号信息
        if request.account_id:
            account = xiaohongshu_account_crud.get(db, id=request.account_id)
        else:
            account = xiaohongshu_account_crud.get_current_account(db)
        
        if not account:
            raise HTTPException(status_code=404, detail="未找到指定账号")
        
        # 如果是定时发布，创建发布日志并返回
        if request.schedule_time:
            # TODO: 集成定时任务调度
            raise HTTPException(status_code=501, detail="定时发布功能暂未实现")
        
        # 立即发布
        result = await xiaohongshu_service.publish_post(
            title=request.title,
            content=request.content,
            images=request.images or []
        )
        
        # 创建发布日志
        log = xiaohongshu_publish_log_crud.create_publish_log(
            db,
            account_id=account.id,
            post_id=0,  # 如果没有关联的post_id，使用0
            title=request.title,
            content=request.content,
            images=request.images,
            tags=request.tags
        )
        
        if result["success"]:
            # 更新发布日志为成功
            xiaohongshu_publish_log_crud.update_publish_status(
                db,
                log_id=log.id,
                status="success"
            )
            
            return PublishResponse(
                success=True,
                message="发布成功",
                log_id=log.id
            )
        else:
            # 更新发布日志为失败
            xiaohongshu_publish_log_crud.update_publish_status(
                db,
                log_id=log.id,
                status="failed",
                error_message=result["message"]
            )
            
            return PublishResponse(
                success=False,
                message=result["message"],
                log_id=log.id
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"发布失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/publish/logs", response_model=PublishLogListResponse)
def get_publish_logs(account_id: Optional[int] = None, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取发布日志"""
    try:
        if account_id:
            logs = xiaohongshu_publish_log_crud.get_by_account_id(db, account_id=account_id, skip=skip, limit=limit)
            total = db.query(xiaohongshu_publish_log_crud.model).filter(
                xiaohongshu_publish_log_crud.model.account_id == account_id
            ).count()
        else:
            logs = xiaohongshu_publish_log_crud.get_multi(db, skip=skip, limit=limit)
            total = db.query(xiaohongshu_publish_log_crud.model).count()
        
        return PublishLogListResponse(
            success=True,
            logs=logs,
            total=total
        )
    except Exception as e:
        logger.error(f"获取发布日志失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/publish/logs/recent", response_model=PublishLogListResponse)
def get_recent_publish_logs(days: int = 7, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取最近的发布日志"""
    try:
        logs = xiaohongshu_publish_log_crud.get_recent_logs(db, days=days, skip=skip, limit=limit)
        total = len(logs)  # 简化处理，实际应该查询总数
        
        return PublishLogListResponse(
            success=True,
            logs=logs,
            total=total
        )
    except Exception as e:
        logger.error(f"获取最近发布日志失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/publish/logs/failed", response_model=PublishLogListResponse)
def get_failed_publish_logs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取失败的发布日志"""
    try:
        logs = xiaohongshu_publish_log_crud.get_failed_logs(db, skip=skip, limit=limit)
        total = db.query(xiaohongshu_publish_log_crud.model).filter(
            xiaohongshu_publish_log_crud.model.status == "failed"
        ).count()
        
        return PublishLogListResponse(
            success=True,
            logs=logs,
            total=total
        )
    except Exception as e:
        logger.error(f"获取失败发布日志失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/stats", response_model=StatsResponse)
def get_stats(account_id: Optional[int] = None, db: Session = Depends(get_db)):
    """获取统计信息"""
    try:
        account_stats = None
        publish_stats = None
        
        if account_id:
            account = xiaohongshu_account_crud.get(db, id=account_id)
        else:
            account = xiaohongshu_account_crud.get_current_account(db)
        
        if account:
            account_stats = AccountStats(
                followers=account.followers,
                following=account.following,
                posts=account.posts,
                likes=account.likes
            )
            
            # 获取发布统计
            logs = xiaohongshu_publish_log_crud.get_by_account_id(db, account_id=account.id, skip=0, limit=1000)
            
            total_posts = len(logs)
            success_posts = len([log for log in logs if log.status == "success"])
            failed_posts = len([log for log in logs if log.status == "failed"])
            pending_posts = len([log for log in logs if log.status == "pending"])
            
            total_views = sum(log.views for log in logs)
            total_likes = sum(log.likes for log in logs)
            total_comments = sum(log.comments for log in logs)
            total_shares = sum(log.shares for log in logs)
            
            publish_stats = PublishStats(
                total_posts=total_posts,
                success_posts=success_posts,
                failed_posts=failed_posts,
                pending_posts=pending_posts,
                total_views=total_views,
                total_likes=total_likes,
                total_comments=total_comments,
                total_shares=total_shares
            )
        
        return StatsResponse(
            success=True,
            account_stats=account_stats,
            publish_stats=publish_stats
        )
    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/test/browser")
async def test_browser():
    """测试浏览器功能"""
    try:
        # 测试浏览器初始化
        if not xiaohongshu_service.is_initialized:
            success = await xiaohongshu_service.initialize()
            if not success:
                return {"success": False, "message": "浏览器初始化失败"}
        
        return {"success": True, "message": "浏览器测试成功"}
    except Exception as e:
        logger.error(f"浏览器测试失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/browser/reset")
async def reset_browser():
    """重置浏览器实例"""
    try:
        # 强制关闭当前浏览器
        await xiaohongshu_service.force_close()
        
        # 重新初始化浏览器
        init_success = await xiaohongshu_service.initialize()
        
        if init_success:
            return {
                "success": True,
                "message": "浏览器已成功重置，Firefox实例已重新初始化"
            }
        else:
            return {
                "success": False,
                "message": "浏览器重置失败，无法重新初始化Firefox实例"
            }
            
    except Exception as e:
        logger.error(f"Browser reset failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/browser/status")
async def get_browser_status():
    """获取浏览器状态"""
    try:
        is_initialized = xiaohongshu_service.is_initialized
        is_connected = False
        
        if xiaohongshu_service.browser:
            try:
                # 检查浏览器是否有可用页面
                pages = xiaohongshu_service.browser.pages
                is_connected = bool(pages and pages[0])
            except:
                is_connected = False
        
        # 获取页面数量信息
        page_count = 0
        active_pages_count = 0
        if xiaohongshu_service.browser:
            try:
                page_count = len(xiaohongshu_service.browser.pages)
                active_pages_count = len(xiaohongshu_service.active_pages)
            except:
                pass
        
        return {
            "success": True,
            "data": {
                "is_initialized": is_initialized,
                "is_connected": is_connected,
                "browser_type": "Firefox",
                "persistent_context": True,
                "user_data_dir": xiaohongshu_service.user_data_dir,
                "page_count": page_count,
                "active_pages_count": active_pages_count,
                "max_pages": xiaohongshu_service.max_pages
            }
        }
        
    except Exception as e:
        logger.error(f"Get browser status failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/browser/cleanup-pages")
async def cleanup_pages():
    """清理多余的浏览器页面"""
    try:
        if not xiaohongshu_service.is_initialized or not xiaohongshu_service.browser:
            return {
                "success": False,
                "message": "浏览器未初始化"
            }
        
        # 获取清理前的页面数量
        pages_before = len(xiaohongshu_service.browser.pages)
        
        # 执行页面清理
        await xiaohongshu_service._cleanup_excess_pages()
        
        # 获取清理后的页面数量
        pages_after = len(xiaohongshu_service.browser.pages)
        pages_cleaned = pages_before - pages_after
        
        return {
            "success": True,
            "message": f"页面清理完成，清理了 {pages_cleaned} 个页面",
            "data": {
                "pages_before": pages_before,
                "pages_after": pages_after,
                "pages_cleaned": pages_cleaned,
                "active_pages_count": len(xiaohongshu_service.active_pages)
            }
        }
        
    except Exception as e:
        logger.error(f"Cleanup pages failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))